package com.hmyd.hmyd_android.fragment;

import java.lang.reflect.Type;
import java.text.NumberFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Bank;
import com.hmyd.hmyd_android.dto.BankCard;
import com.hmyd.hmyd_android.dto.Capital;
import com.hmyd.hmyd_android.dto.CouponCount;
import com.hmyd.hmyd_android.easydialog.EasyDialog;
import com.hmyd.hmyd_android.ui.AccountOverviewActivity;
import com.hmyd.hmyd_android.ui.BankActivity;
import com.hmyd.hmyd_android.ui.BillRedeemActivity;
import com.hmyd.hmyd_android.ui.CouponListActivity;
import com.hmyd.hmyd_android.ui.FinancingDetailsListActivity;
import com.hmyd.hmyd_android.ui.HmWalletListActivity;
import com.hmyd.hmyd_android.ui.InvestmentListActivity;
import com.hmyd.hmyd_android.ui.MyBackActivity;
import com.hmyd.hmyd_android.ui.MyScoreActivity;
import com.hmyd.hmyd_android.ui.RechargeActivity;
import com.hmyd.hmyd_android.ui.WithdrawalsActivity;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.MyDialog;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 资产
 */
public class AssetsFragment extends BasicFragment implements OnClickListener {
	private final int CAPITAL = 1; // 资产数据
	private final int BANKCARD = 2; // 银行卡信息
	private final int DEPOSIT = 3; // 充值信息
	private final int WITHDRAW = 4; // 取现信息
	private final int COUPON_INTRO = 5; // 现金券使用情况
	private final int GET_BILL_AMOUNT = 6; // 获取是否有赎回金额

	private View root;

	// 累计净收益
	private TextView assets_cumulative_net_income_label;
	private TextView assets_cumulative_net_income;
	// 账户总额
	private TextView assets_total_account;
	private Button bill_redeem;

	// 可用余额
	private TextView assets_available_balance;

	// 小惠钱包
	private TextView assets_wallet;
	
	private MyDialog noBillRedeemDailog;
	
	private Capital capital;
	private Bank bank;
	// 现金券图标
	private ImageView zi_icon_xianq;
	private String canRedeemAmount; // 赎回金额
	private long billPickTime = 0;// 今日赎回到帐时间
	private boolean canRedeem; // 是否可以赎回
	
	private CouponCount couponCount;
	private int redPoint_ID = 1001;// 小红点ID，添加ID便于移除和添加
	private TextView principal_interest_value; // 计息本金
	private TextView principal_uninterest_value; // 未计息本金

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (root == null) {
			root = inflater.inflate(R.layout.fragment_assets, container, false);
			initView();
		}

		// 缓存的rootView需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) root.getParent();
		if (parent != null) {
			parent.removeView(root);
		}
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		setParams();
		super.onActivityCreated(savedInstanceState);

	}

	/**
	 * 初始化视图
	 */
	private void initView() {
		assets_cumulative_net_income_label = (TextView) root
				.findViewById(R.id.assets_cumulative_net_income_label);
		assets_cumulative_net_income = (TextView) root
				.findViewById(R.id.assets_cumulative_net_income);

		assets_total_account = (TextView) root
				.findViewById(R.id.assets_total_account);

		assets_available_balance = (TextView) root
				.findViewById(R.id.assets_available_balance);
		assets_wallet = (TextView) root.findViewById(R.id.assets_wallet);
		zi_icon_xianq = (ImageView) root.findViewById(R.id.zi_icon_xianq);
		principal_interest_value = (TextView) root.findViewById(R.id.principal_interest_value);
		principal_uninterest_value = (TextView) root.findViewById(R.id.principal_uninterest_value);
		bill_redeem = (Button) root.findViewById(R.id.bill_redeem);

		ViewGroup.LayoutParams lp = root.findViewById(R.id.recharge)
				.getLayoutParams();
		int width = Utils.screenWidth_ * 35 / 100;
//		// 服务器最新版本大于3.1.0才显示票据赎回按钮
//		int version = Integer.parseInt(AppBasic.version.newVersion.replace(".", ""));
//		if(version < 310) {
//			bill_redeem.setVisibility(View.GONE);
//			width = Utils.screenWidth_ * 35 / 100;
//		} else {
//			lp = bill_redeem.getLayoutParams();
//			lp.width = width;
//			bill_redeem.setLayoutParams(lp);
//			bill_redeem.setVisibility(View.VISIBLE);
//		}
				
		
		
		lp = root.findViewById(R.id.recharge).getLayoutParams();
		lp.width = width;

		root.findViewById(R.id.recharge).setLayoutParams(lp);

		lp = root.findViewById(R.id.assets_cash).getLayoutParams();
		lp.width = width;
		root.findViewById(R.id.assets_cash).setLayoutParams(lp);
		
		
		int height = Utils.screenHeight_ - 160;

		// 分辨率特别大的手机自适配
		if (height > 1080) {
			lp = root.findViewById(R.id.top).getLayoutParams();
			lp.height = height * 300 / 550;

			root.findViewById(R.id.top).setLayoutParams(lp);

			lp = root.findViewById(R.id.menu1).getLayoutParams();
			lp.height = height * 125 / 550;

			root.findViewById(R.id.menu1).setLayoutParams(lp);

			lp = root.findViewById(R.id.menu2).getLayoutParams();
			lp.height = height * 125 / 550;
			root.findViewById(R.id.menu2).setLayoutParams(lp);
			lp = root.findViewById(R.id.my_bill_status_layout).getLayoutParams();
			lp.height = height*50/550;
			root.findViewById(R.id.my_bill_status_layout).setLayoutParams(lp);
		}
		
		root.findViewById(R.id.my_hm_wallet).setOnClickListener(this);
	}

	private static int[] ids = { R.id.assets_cumulative_net_income_label,
			R.id.assets_cumulative_net_income_label_mark,
			R.id.assets_cumulative_net_income_detail,
			R.id.assets_total_account_lab, R.id.assets_wallet_lab,
			R.id.recharge, R.id.assets_cash, R.id.bill_redeem,
			R.id.financing_details, R.id.investment, R.id.coupons,
			R.id.back_list, R.id.bank_card_list, R.id.score_list,
			R.id.assets_total_layout ,R.id.my_hm_wallet};

	/**
	 * 设置属性
	 * 
	 * @param root
	 */
	private void setParams() {
		for (int i = 0; i < ids.length; i++) {
			root.findViewById(ids[i]).setOnClickListener(this);
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		if (AppBasic.isLogin) {
			// 资产明细数据
			onRequest(CAPITAL, UrlConstant.CAPITALDETAIL, HttpMethod.GET, null);
			// 获取现金券使用情况
			onRequest(COUPON_INTRO, UrlConstant.COUPONCOUNT, HttpMethod.GET, null);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.assets_cumulative_net_income_label:
		case R.id.assets_cumulative_net_income_label_mark:
			incomeLabClick(v);
			break;
		case R.id.assets_cumulative_net_income_detail:
			incomeClick(v);
			break;
		case R.id.assets_total_layout:
		case R.id.assets_total_account_lab:
			accountLabClick(v);
			break;
//		case R.id.assets_wallet_lab:
//			walletLabClick(v);
//			break;
		case R.id.recharge:
			rechargeClick(v);
			break;
		case R.id.assets_cash:
			cashClick(v);
			break;
		case R.id.financing_details:
			financingClick(v);
			break;
		case R.id.investment:
			investmentClick(v);
			break;
		case R.id.coupons:
			couponsClick(v);
			break;
		case R.id.back_list:
			backClick(v);
			break;
		case R.id.bank_card_list:
			cardClick(v);
			break;
		case R.id.score_list:
			scoreClick(v);
			break;
		case R.id.bill_redeem:
			billClick(v);
			break;
		case R.id.my_hm_wallet:
			myHmWalletClick(v);
			break;
		default:
			break;
		}
	}

	// 累计净收益提示
	private void incomeLabClick(final View v) {
		if (Utils.getSDKVersion() > 10) {
			showTipLayout(assets_cumulative_net_income_label,
					getString(R.string.tip_layout));
		}
	}

	// 收益饼图提示
	private void incomeClick(View v) {
		Intent intent = new Intent(getActivity(),
				FinancingDetailsListActivity.class);
		intent.putExtra("init", true);
		startActivity(intent);
	}

	// 账户概况提示
	private void accountLabClick(View v) {
			startActivity(new Intent(getActivity(),
					AccountOverviewActivity.class));
	}

	// 小惠钱包提示
	private void walletLabClick(View v) {
		if (Utils.getSDKVersion() > 10) {
			showTipLayout(v, getString(R.string.tip_layout_wallet));
		}
	}

	// 充值
	private void rechargeClick(View v) {
		// if(capital.isBoundCard && capital.isAccountisVerify) {
		// startActivity(RechargeActivity.getIntent(getActivity(),
		// assets_available_balance.getText().toString()));
		// } else if(!capital.isAccountisVerify){
		// MyToast.showHMToast(getActivity(), false, "请先进行用户实名制");
		// startActivity(new Intent(getActivity(),CreateAccountActivity.class));
		// return;
		// } else if(!capital.isBoundCard) {
		// onRequest(BANKCARD, UrlConstant.BANKCARD, HttpMethod.POST, null);
		// }

		onRequest(DEPOSIT, UrlConstant.DEPOSIT, HttpMethod.GET, null);
	}

	// 取现
	private void cashClick(View v) {
		onRequest(WITHDRAW, UrlConstant.WITHDRAW, HttpMethod.POST, null);

		/*
		 * if (capital != null) { if(capital.isBoundCard &&
		 * capital.isAccountisVerify) {
		 * startActivity(WithdrawalsActivity.getIntent(getActivity(),
		 * capital.availableBalance+"")); } else if(!capital.isAccountisVerify){
		 * MyToast.showHMToast(getActivity(), false, "请先进行用户实名制");
		 * startActivity(new Intent(getActivity(),CreateAccountActivity.class));
		 * return; } else if(!capital.isBoundCard) { onRequest(BANKCARD,
		 * UrlConstant.BANKCARD, HttpMethod.POST, null); } }
		 */
	}

	// 资金明细
	private void financingClick(View v) {
		startActivity(new Intent(getActivity(),
				FinancingDetailsListActivity.class));
	}

	// 投资列表
	private void investmentClick(View v) {
		startActivity(new Intent(getActivity(), InvestmentListActivity.class));
	}

	// 现金券
	private void couponsClick(View v) {
		Intent intent = new Intent(getActivity(), CouponListActivity.class);
		intent.putExtra("couponCount", couponCount);
		startActivity(intent);
	}

	// 我的回款
	private void backClick(View v) {
		startActivity(new Intent(getActivity(), MyBackActivity.class));
	}

	// 银行卡
	private void cardClick(View v) {
		onRequest(BANKCARD, UrlConstant.BANKCARD, HttpMethod.POST, null);

		/*
		 * if(capital.isBoundCard && capital.isAccountisVerify) {
		 * startActivity(new Intent(getActivity(), BankActivity.class)); } else
		 * if(!capital.isAccountisVerify){ MyToast.showHMToast(getActivity(),
		 * false, "请先进行用户实名制"); startActivity(new
		 * Intent(getActivity(),CreateAccountActivity.class)); return; } else
		 * if(!capital.isBoundCard) { onRequest(BANKCARD, UrlConstant.BANKCARD,
		 * HttpMethod.POST, null); }
		 */
	}

	// 我的积分
	private void scoreClick(View v) {

		startActivity(new Intent(getActivity(), MyScoreActivity.class));
	}

	// 票据赎回
	private void billClick(View v) {
		// TODO
		onRequest(GET_BILL_AMOUNT, UrlConstant.BILL_AVAILABLE_AMOUNT, HttpMethod.GET, null);
		// if(capital.isBoundCard && capital.isAccountisVerify) {
		
		// } else if(!capital.isAccountisVerify){
		// MyToast.showHMToast(getActivity(), false, "请先进行用户实名制");
		// startActivity(new Intent(getActivity(),CreateAccountActivity.class));
		// return;
		// } else if(!capital.isBoundCard) {
		// onRequest(BANKCARD, UrlConstant.BANKCARD, HttpMethod.POST, null);
		// }
	}
	
	// 小惠钱包详情列表
	private void myHmWalletClick(View v) {
		startActivity(new Intent(getActivity(),HmWalletListActivity.class));
	}

	@Override
	public void onPostSuccess(int postId, String msg) {
		Gson gson = new Gson();
		Intent intent = new Intent();
		switch (postId) {
		case CAPITAL:
			Type type = new TypeToken<Capital>() {
			}.getType();
			capital = gson.fromJson(msg, type);
			if (capital != null) {
				assets_cumulative_net_income.setText(NumberFormat.getInstance()
						.format(capital.incomeTotal));
				assets_total_account.setText(NumberFormat.getInstance().format(
						capital.balance));
				assets_available_balance.setText(NumberFormat.getInstance()
						.format(capital.availableBalance));
				assets_wallet.setText(NumberFormat.getInstance().format(
						capital.hmWallet));
				String principal_interest_value_str = NumberFormat.getInstance().
						format(capital.PI);
				String principal_uninterest_value_str = NumberFormat.getInstance()
						.format(capital.NPI);
				principal_interest_value.setText(principal_interest_value_str);
				principal_uninterest_value.setText(principal_uninterest_value_str);
//				if(capital.PI <= 0 && capital.NPI <= 0) {
//					bill_redeem.setEnabled(false);
//					bill_redeem.setBackgroundResource(R.color.light_gray_line);
//				} else {
//					bill_redeem.setEnabled(true);
//					bill_redeem.setBackgroundResource(R.drawable.recharge_shape_selector);
//				}
			}

			break;
		case BANKCARD:
			java.lang.reflect.Type type2 = new TypeToken<BankCard>() {
			}.getType();
			BankCard bankCard = gson.fromJson(msg, type2);

			intent.setClass(getActivity(), BankActivity.class);
			intent.putExtra("bank_card", bankCard);
			getActivity().startActivity(intent);
			break;
		case DEPOSIT:
			java.lang.reflect.Type type3 = new TypeToken<Bank>() {
			}.getType();
			bank = gson.fromJson(msg, type3);

			intent.setClass(getActivity(), RechargeActivity.class);
			intent.putExtra("bank", bank);
			intent.putExtra("available_balance", assets_available_balance
					.getText().toString());
			getActivity().startActivity(intent);
			break;
		case WITHDRAW:
			java.lang.reflect.Type type4 = new TypeToken<Bank>() {
			}.getType();
			bank = gson.fromJson(msg, type4);

			intent.setClass(getActivity(), WithdrawalsActivity.class);
			intent.putExtra("bank", bank);
			intent.putExtra("available_balance", capital.availableBalance + "");
			getActivity().startActivity(intent);
			break;
		case COUPON_INTRO:
			java.lang.reflect.Type type5 = new TypeToken<CouponCount>() {
			}.getType();
			couponCount = gson.fromJson(msg, type5);
			if(couponCount.usable > 0) {
				addRedPoint(zi_icon_xianq);
			} else {
				removeRedPoint(zi_icon_xianq);
			}
			break;
		case GET_BILL_AMOUNT:
			try {
				JSONObject json = new JSONObject(msg);
				canRedeemAmount = json.getString("canRedeemAmount");
				billPickTime = json.getLong("billPickTime");
				canRedeem = canRedeemAmount != null && !canRedeemAmount.equals("null") && 
							!canRedeemAmount.trim().equals("") && Double.valueOf(canRedeemAmount) > 0;
				Intent intent1 = new Intent();
				intent1.setClass(getActivity(), BillRedeemActivity.class);
				intent1.putExtra("canRedeemAmount", canRedeemAmount);
				intent1.putExtra("billPickTime", billPickTime);
				intent1.putExtra("canRedeem", canRedeem);
				startActivity(intent1);
//				if(canRedeem) {
//					
//				} else {
//					noBillRedeemDailog = new MyDialog(getActivity(), R.layout.view_bill_confirm);
//					RelativeLayout mDailogContent = (RelativeLayout) noBillRedeemDailog.getContentView();
//					Button m_sure = (Button) mDailogContent.findViewById(R.id.m_sure);
//					Button m_cancle =  (Button) mDailogContent.findViewById(R.id.m_cancle);
//					ImageView m_close = (ImageView) mDailogContent.findViewById(R.id.m_close);
//					TextView m_content = (TextView) mDailogContent.findViewById(R.id.m_content);
//					m_content.setText("您没有可赎回的票据");
//					m_sure.setText(">点击查看赎回记录");
//					m_sure.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
//					m_cancle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
//					m_sure.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							Intent intent = new Intent(AssetsFragment.this.getActivity(),WithdrawalsHistoryListActivity.class);
//							intent.putExtra("isFromBill", 1);
//							startActivity(intent);
//							noBillRedeemDailog.dismiss();
//						}
//					});
//					m_close.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							noBillRedeemDailog.dismiss();
//						}
//					});
//					m_cancle.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							noBillRedeemDailog.dismiss();
//						}
//					});
//					noBillRedeemDailog.show();
//				}
			} catch (JSONException e) {
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 移除小红点
	 * @param view
	 */
	public void removeRedPoint(View view) {
		RelativeLayout parentLayout = (RelativeLayout) view.getParent();
		if(parentLayout.findViewById(redPoint_ID) == null) {
			return;
		}
		parentLayout.removeView(parentLayout.findViewById(redPoint_ID));
	}

	@Override
	public void onPostFailure(int postId, String msg) {
	}

	/**
	 * 给控件增加小红点
	 * @param view
	 */
	public void addRedPoint(View view) {
		RelativeLayout parentLayout = (RelativeLayout) view.getParent();
		TextView redPoint = new TextView(getActivity());
		redPoint.setId(redPoint_ID);
		redPoint.setBackgroundResource(R.drawable.shape_red_point);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);

		// 设置小红点大小	
		params.width = Utils.screenWidth_ / 45;
		params.height = Utils.screenWidth_ / 45;
		params.addRule(RelativeLayout.ALIGN_RIGHT, view.getId());
		params.rightMargin = (int) Utils.getRawSize(getActivity(), TypedValue.COMPLEX_UNIT_DIP, 13);
		params.topMargin =  (int) Utils.getRawSize(getActivity(), TypedValue.COMPLEX_UNIT_DIP, 13);
		
		redPoint.setLayoutParams(params);
		
		parentLayout.addView(redPoint);
	}

	EasyDialog dialog;

	/**
	 * 显示提示信息
	 */
	private void showTipLayout(View v, String str) {
		View root = LayoutInflater.from(getActivity()).inflate(
				R.layout.layout_tip, null);
		((TextView) root.findViewById(R.id.tip_layout)).setText(str);
		((TextView) root.findViewById(R.id.tip_layout))
				.setTextColor(Color.WHITE);
		root.setPadding(20, 10, 20, 10);

		dialog = new EasyDialog(getActivity())
				.setBackgroundColor(getResources().getColor(R.color.tran))
				.setLayout(root) // 设置布局文件
				.setLocationByAttachedView(v) // 设置显示位置
				.setTouchOutsideDismiss(true) // 设置触摸外部是否取消
				.setMatchParent(false) // 设置是否填充
				.setMarginLeftAndRight(2, 0) // 距离屏幕位置
				.setOutsideColor(Color.TRANSPARENT) // 设置对话框外部背景颜色
				.setMarginLeftAndRight(0, 0).show();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(noBillRedeemDailog != null || noBillRedeemDailog.isShowing()) {
			noBillRedeemDailog.dismiss();
			noBillRedeemDailog = null;
		}
	}
}
